package com.ruoyi.askcase.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.askcase.domain.AskCase;
import com.ruoyi.askcase.service.IAskCaseService;
import com.ruoyi.asktreat.domain.AskTreat;
import com.ruoyi.asktreat.service.IAskTreatService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.omchannel.domain.OmChannel;
import com.ruoyi.omchannel.service.IOmChannelService;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 病例管理Controller
 * 
 * @author ruoyi
 * @date 2025-02-08
 */
@RestController
@RequestMapping("/mp/ask/case")
public class MpAskCaseController extends BaseController
{
    @Autowired
    private IAskCaseService askCaseService;

    @Autowired
    private IAskTreatService askTreatService;

    @Autowired
    private IOmChannelService omChannelService;


    //小程序端 添加问诊病例
    @PostMapping("/add")
    public AjaxResult add(@RequestBody AskCase askCase)
    {

        Random random = new Random();
        // 生成100000到999999之间的随机数，确保是6位数
        int randomNumber = 100000 + random.nextInt(900000);
        String code6 = ""+randomNumber;
//        String uuid = UUID.randomUUID().toString();
        askCase.setCaseCode6(code6);

        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 20);
        askCase.setCaseUuid(uuid);
        //form 里获取
        String input = askCase.getCaseChannelUUid();

        if(input == null){
            //没有扫码
        }else{
            //扫码了
            OmChannel omChannel = omChannelService.getInfo(input);
            if(null == omChannel){
                return error("渠道错误");
            }
            Long caseChannelid = omChannel.getChannelId();
            askCase.setCaseChannelid(caseChannelid);
        }
        return toAjax(askCaseService.insertAskCase(askCase));
    }


    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody AskCase askCase)
    {
        return toAjax(askCaseService.updateAskCase(askCase));
    }




    //更新一个版本 首页 只希显示案例
    //小程序-首页所有病例列表-含2个治疗
    @GetMapping("/getHomecaseList")
    public AjaxResult getHomecaseList() throws Exception {
        //logger.info(JSON.toJSONString(inMap));
        List<HashMap<String,Object>> list = askCaseService.getHomecaseList(3);

        for(HashMap<String,Object> item :list){
            List<HashMap<String, Object>> list2 = askCaseService.getTwoTreatsBycasId(Long.valueOf(item.get("case_id").toString()));

            //外面的item 其实类似 内部treat 的 小map

            for (HashMap<String, Object> map : list2) {
                // 获取 "createtime" 字段的值
                String createTimeObj = map.get("treat_createtime").toString();


                    // 将 "T" 替换为 " "
                    String createTimeStr = ((String) createTimeObj).replace("T", " ");
                    // 更新 map 中的 "createtime" 字段
                    map.put("treat_createtime", createTimeStr);

            }

            item.put("treatList",list2);

        }
            return success(list);
    }

    //小程序-我的所有病例列表-含2个治疗
    @PostMapping("/getMycaseList")
    public AjaxResult getMycaseList(@RequestBody HashMap<String,Object> inMap) throws Exception {
        logger.info(JSON.toJSONString(inMap));
        if (inMap.get("openid")  == null) {
            return error("openid 没有传");
        }
        String openid = inMap.get("openid").toString();
        //不用联表
        // List<HashMap<String,Object>> list2222 = askCaseService.getMycaseListJoin(openid);
        List<HashMap<String,Object>> list = askCaseService.getMycaseList(openid);
        for(HashMap<String,Object> item :list){
            List<HashMap<String, Object>> list2 = askCaseService.getTwoTreatsBycasId(Long.valueOf(item.get("case_id").toString()));
            item.put("treatList",list2);

        }
        return success(list);
    }

    //我的某个病例的所有治疗列表。
    @PostMapping("/getMycaseOne")
    public AjaxResult getMycaseOne(@RequestBody HashMap<String,Object> inMap) throws Exception {
        logger.info(JSON.toJSONString(inMap));
        if (inMap.get("openid")  == null) {
            return error("openid 没有传");
        }
        if (inMap.get("caseid")  == null) {
            return error("caseid 没有传");
        }
        String openid = inMap.get("openid").toString();
        Long caseid = Long.valueOf(inMap.get("caseid").toString());
        AskCase askCase = askCaseService.selectAskCaseByCaseId(caseid);
        //
        AskTreat askTreat = new AskTreat();
        askTreat.setTreatCaseid(caseid);
        List<AskTreat> list = askTreatService.selectAskTreatList(askTreat);
        askCase.setTreatList(list);
        return success(askCase);
    }

    //添加case

    @GetMapping("/list")
    public TableDataInfo list(AskCase askCase)
    {
        startPage();
        List<AskCase> list = askCaseService.selectAskCaseList(askCase);
        for(AskCase item :list){
            List<HashMap<String, Object>> list2 = askCaseService.getTwoTreatsBycasId(item.getCaseId());
            item.setTreatListMap(list2);

        }
        return getDataTable(list);
    }

    @GetMapping("/v")
    public AjaxResult v()
    {
        return success("1.0.3");
    }


    @GetMapping(value = "/{caseId}")
    public AjaxResult getInfo(@PathVariable("caseId") Long caseId)
    {
        return success(askCaseService.selectAskCaseByCaseId(caseId));
    }

    @GetMapping(value = "/caseinfo")
    public AjaxResult caseinfo(
            @RequestParam(value = "caseid") Long caseid,
            @RequestParam(value = "openid") String openid
    )
    {
        logger.info("参数{}-{}",caseid,openid);
        AskCase askCase=  askCaseService.selectAskCaseByCaseId(caseid);
        if(askCase.getCaseOpenid().equals(openid)){
            //return success(askCaseService.selectAskCaseByCaseId(caseid));
            return success(askCase);
        }else{
            //500
//            //return error("对不起，无权查看");


            //说明是案例
            if (askCase.getCaseRemark().equals("1")){
                String phoneNumber = askCase.getCasePhone();
                StringBuilder hiddenPhoneNumber = new StringBuilder();

                // 添加前缀
                hiddenPhoneNumber.append(phoneNumber.substring(0, 3));
                hiddenPhoneNumber.append("****");

                // 添加后缀
                hiddenPhoneNumber.append(phoneNumber.substring(7));
                askCase.setCasePhone(hiddenPhoneNumber.toString());
                String cname = maskChineseName(askCase.getCaseUname());
                askCase.setCaseUname(cname);
                //askCase.setCaseUage(0);
                return success(askCase);
            }
            return error("无权访问");
        }
        //return success(askCaseService.selectAskCaseByCaseId(caseid));


    }

    public static String maskChineseName(String name) {
        if (name == null || name.length() <= 1) {
            return name; // 如果名字为空或者只有一个字符，则直接返回原名
        } else {
            // 使用StringBuilder构建新字符串，先添加第一个字符
            StringBuilder maskedName = new StringBuilder(name.substring(0, 1));
            // 然后添加三个星号
            for (int i = 0; i < 3; i++) {
                maskedName.append('*');
            }
            return maskedName.toString();
        }
    }



}
